<template>
	<BasicDrawer v-model:show="showModal" :title="menuTitle" :width="'80%'">
		<n-form ref="formRef" :label-width="80" :model="form" :rules="rules" size="medium">
			<n-form-item label="字典名称" path="dict_name">
				<n-input v-model:value="form.dict_name" placeholder="输入用户名" />
			</n-form-item>
			<n-form-item label="字典值" path="dict_code">
				<n-input v-model:value="form.dict_code" placeholder="输入登录名" />
			</n-form-item>
			<n-form-item label="排序" path="age">
				<n-input v-model:value="form.age" placeholder="请输入年龄" />
			</n-form-item>
		</n-form>
		<template v-slot:footer>
			<n-button @click="handleCancel">取消</n-button>
			<n-button class="ml-10" @click="handleConfirm" :loading="btnLoading" type="primary">确定</n-button>
		</template>
	</BasicDrawer>
</template>

<script setup lang="ts">
	import { unref, ref, reactive, defineExpose } from 'vue'
	import { useMessage, NButton, NSpace, FormInst } from 'naive-ui'
	import { BasicDrawer } from "@/components/Common/BasicDrawer"
	import _ from "lodash-es"
	import { RowData } from 'naive-ui/es/data-table/src/interface'
	import { addOrUpdateDict } from "@/api/system"
	const message = useMessage()
	const emits = defineEmits([
		"refresh"
	])
	const showModal = ref(false)
	const roleId = ref<string>()
	const formRef = ref<FormInst | null>(null)
	const formData = () => ({
		dict_name: null,
		dict_code: null,
		sort: null
	})
	let form = reactive(formData())
	const rules = {
		dict_name: {
			required: true,
			trigger: ['blur', 'input'],
			message: '请输入字典名称'
		},
		dict_code: {
			required: true,
			trigger: ['blur', 'input'],
			message: '请输入字典值'
		}
	}
	const menuTitle = ref<String>("字典新增")
	/**
	 * @param {Object} row
	 * 打开弹窗
	 */
	const treeClassId = ref(null)
	function open(row : RowData, flag:Boolean | null) {
		showModal.value = true
		if (!flag) {
			menuTitle.value = '字典编辑'
			roleId.value = row.id
			Object.assign(unref(form), row)
		} else {
			form = Object.assign(unref(form), formData())
			form.class_id = row.class_id
			formRef.value?.restoreValidation()
			menuTitle.value = '字典新增'
		}
		treeClassId.value = row.class_id
	}
	function handleCancel() {
		showModal.value = false
	}
	/**
	 * 保存
	 */
	const btnLoading = ref<Boolean>(false)
	function handleConfirm(e : MouseEvent) {
		e.preventDefault()
		formRef.value?.validate((errors) => {
			if (!errors) {
				btnLoading.value = true
				addOrUpdateDict(form).then(res => {
					message.success('保存成功')
					btnLoading.value = false
					showModal.value = false
					emits('refresh',{class_id:treeClassId.value})
				})
			} else {
				message.error('验证失败')
			}
		})

	}

	defineExpose({
		open
	})
</script>

<style>
</style>